<?php

namespace Service\MnActivityService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\Vip;
use App\Model\BbcModel\ActivityStore;
use App\Model\BbcModel\MnStoreGoods;
use App\Model\BbcModel\MnActivityGoods;
use App\Model\BbcModel\DistributorPrice;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\MnActivity;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\Activity;
use App\Model\BbcModel\StoreActivity;
use App\Model\BbcModel\ActivitySend;
use App\Model\BbcModel\ActivityDrop;
use App\Model\BbcModel\ActivityDiscount;
use App\Model\BbcModel\ActivityBook;
use Hyperf\DbConnection\Db;
use Service\GoodsService\MnGoodsService;

/**
 * TO C/B 活动专区
 * @author hj
 */
class ActivityService extends BaseService 
{
    /**
     * 获取活动列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getActivityList(array $param)
    {
        $check = Mnuser::validate($param);
        if ($check['code'] != Normal::SUC) {
            return $check;
        }
        $info  = $check['data'];
        $model = MnActivity::where('mn_sid', $info['id'])->where('df', 0);
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        if (isset($param['status']) && in_array($param['status'], ['1', '2', '3'])) {
            $model = $model->where('status', $param['status']);
        }
        if (isset($param['search']) && !empty($param['search'])) {
            $model = $model->where('name', 'like', "%{$param['search']}%");
        }
        if (isset($param['type']) && in_array($param['type'], ['1', '2'])) {
            $model = $model->where('type', $param['type']);
        }
        $result = $model->orderBy('id', 'desc')->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功', ['data' => [], 'count' => 0]);
        }
        return Normal::returnCode(Normal::SUC, '获取成功', ['data' => $result->items(), 'count' => $result->total()]);
    }

    /**
     * 新增活动
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function addActivity(array $param) 
    {
        $check = Mnuser::validate($param);
        if ($check['code'] != Normal::SUC) {
            return $check;
        }
        $info = $check['data'];
        if (!isset($param['name']) || empty($param['name'])) {
            return Normal::returnCode(Normal::FAIL, 'expect param name');
        }
        if (!isset($param['startdate']) || empty($param['startdate'])) {
            return Normal::returnCode(Normal::FAIL, 'expect param startdate');
        }
        if (!isset($param['enddate']) || empty($param['enddate'])) {
            return Normal::returnCode(Normal::FAIL, 'expect param enddate');
        }
        if (!isset($param['type']) || !in_array($param['type'], ['1', '2'])) {
            return Normal::returnCode(Normal::FAIL, 'expect param type');
        }
        if (!isset($param['goods']) || empty($param['goods'])) {
            return Normal::returnCode(Normal::FAIL, 'expect param goods');
        }
        $startdate = $param['startdate'];
        $enddate   = $param['enddate'];
        $goods     = json_decode($param['goods'], true);
        $goods_ids = array_column($goods, 'goods_id');
        $goodsAll  = Goods::whereIn('id', $goods_ids)->select(['id', 'medicinal', 'price_store', 'name', 'price_cost', 'is_trade'])->get()->toArray();
        if ($goodsAll) {
            $goodsAll = array_column($goodsAll, null, 'id');
        }
        $levelPriceAll = DistributorPrice::where('level_id', $info['level'])->whereIn('goods_id', $goods_ids)->get()->pluck('price', 'goods_id')->toArray();
        $existByGoods  = [];
        $existAll      = MnActivityGoods::query()->from((new MnActivityGoods)->getTable() . ' as mnag')
            ->join("ly_mn_activity as mna", 'mnag.mn_activity_id', '=', 'mna.id')
            ->leftJoin('ly_goods as gs', 'gs.id', '=', 'mnag.goods_id')
            ->where('mna.mn_sid', $info['id'])->whereIn('mnag.goods_id', $goods_ids)->where('mnag.df', 0)
            ->where(function ($query) use ($startdate, $enddate) {
                $query->whereBetween('mna.startdate', [$startdate, $enddate])->orWhereBetween('mna.enddate', [$startdate, $enddate]);
            })->select(['mna.id', 'mnag.goods_id', 'gs.name as goods_name', 'mna.enddate'])->get()->toArray();
        if ($existAll) {
            foreach ($existAll as $item) {
                $existByGoods[$item['goods_id']][] = $item;
            }
        }
        foreach ($goods as $key => $value) {
            if ($param['type'] == 2) {
                if (!isset($value['price'])) {
                    return Normal::returnCode(Normal::FAIL, '请设置完商品的特价价格');
                }
                if (!isset($goodsAll[$value['goods_id']])) {
                    continue;
                }
                $goodsType = $goodsAll[$value['goods_id']];
                if ($goodsType['is_trade'] == 0) {
                    if ($value['price'] < $goodsType['price_store']) {
                        return Normal::returnCode(Normal::FAIL, "商品《{$goodsType['name']}》不可低于成本价");
                    }
                }
                if ($goodsType['medicinal'] > 0) {
                    if ($info['level'] > 0) {
                        $levelPrice = $levelPriceAll[$value['goods_id']] ?? '';
                        if (!empty($levelPrice)) {
                            $goodsType['price_store'] = $levelPrice;
                        }
                    }
                    if ($value['price'] < $goodsType['price_store']) {
                        return Normal::returnCode(Normal::FAIL, "商品《{$goodsType['name']}》不可低于成本价");
                    }
                }
                if (($value['price'] < $goodsType['price_cost']) && ($goodsType['is_trade'] == 0)) {
                    return Normal::returnCode(Normal::FAIL, "商品《{$goodsType['name']}》价格低于下限");
                }
            }
            $exist = $existByGoods[$value['goods_id']] ?? [];
            if ($exist) {
                foreach ($exist as $v) {
                    if ($v['enddate'] > time()) {
                        return Normal::returnCode(Normal::FAIL, $v['goods_name'] . '商品在其他可进行时间内的活动中已经存在' . $value['goods_id']);
                    }
                }
            }
        }
        $activityData = [
            'name'      => $param['name'],
            'startdate' => $startdate,
            'enddate'   => $enddate,
            'cd'        => time(),
            'mn_sid'    => $info['id'],
            'type'      => $param['type'],
            'sid'       => getSID(),
        ];
        if ($param['type'] == 1) {
            if (!isset($param['full']) || !isset($param['drop'])) {
                return Normal::returnCode(Normal::FAIL, '请设置满减金额');
            }
            $activityData['full'] = $param['full'];
            $activityData['drop'] = $param['drop'];
        }
        Db::beginTransaction();
        try {
            $mnActivityModel    = MnActivity::make($activityData);
            $mnActivityModelRes = $mnActivityModel->save();
            if (!$mnActivityModelRes) {
                throw new \RuntimeException("活动保存异常");
            }
            $activityGoodsDatra = [];
            foreach ($goods as $val) {
                $activityGoodsDatra[] = [
                    'mn_activity_id' => $mnActivityModel->id,
                    'cd'             => time(),
                    'sid'            => getSID(),
                    'goods_id'       => (int)($val['goods_id']),
                    'price'          => $val['price'],
                ];
            }
            $activityGoodsRes = MnActivityGoods::insert($activityGoodsDatra);
            if (!$activityGoodsRes) {
                throw new \RuntimeException("活动商品保存错误");
            }
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollBack();
            return Normal::returnCode(Normal::FAIL, '操作失败' . $th->getMessage());
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }

    /**
     * 更改活动状态
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function changeStatus(array $param) 
    {
        if (!isset($param['activity_id']) || empty($param['activity_id']) || (preg_match("/^[1-9]\d*$/", (string)$param['activity_id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument activity_id');
        }
        if (!isset($param['status']) || !in_array($param['status'], ['1', '2', '3'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument status');
        }
        $activity = MnActivity::where('id', (int)($param['activity_id']))->first();
        if (!$activity) {
            return Normal::returnCode(Normal::FAIL, '未找到相关活动');
        }
        $activity->status = (int)($param['status']);
        $activity->md     = time();
        $res              = $activity->save();
        if (!$res) {
            return Normal::returnCode(Normal::FAIL, '操作失败');
        }
        return Normal::returnCode(Normal::SUC, '操作成功');
    }

    /**
     * 获取活动商品
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getActivityGoods(array $param)
    {
        if (!isset($param['activity_id']) || empty($param['activity_id']) || (preg_match("/^[1-9]\d*$/", (string)$param['activity_id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument activity_id');
        }
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        $activity = MnActivity::where('id', (int)($param['activity_id']))->first();
        if (!$activity) {
            return Normal::returnCode(Normal::FAIL, '未找到相关活动');
        }
        $result = MnActivityGoods::where('df', 0)->where('mn_activity_id', $activity->id)->orderBy('id', 'desc')->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功', ['data' => [], 'count' => 0]);
        }
        $collection = $result->getCollection();
        $goods_ids  = $collection->pluck('goods_id')->toArray();
        $goodsAll   = Goods::whereIn('id', $goods_ids)->select(['id', 'name', 'price_store'])->get()->toArray();
        if ($goodsAll) {
            $goodsAll = array_column($goodsAll, null, 'id');
        }
        $mnStoreGoodsAll = MnStoreGoods::where('mn_sid', $activity->mn_sid)->whereIn('goods_id', $goods_ids)->pluck('status', 'goods_id')->toArray();
        $level           = Mnuser::where('id', $activity->mn_sid)->value('level');
        $profitAll       = MnStoreGoods::getGoodsAllProfit($activity->mn_sid, $goods_ids, 1, $level);
        $resultArr       = $collection->toArray();
        $resultData      = [];
        foreach ($resultArr as $value) {
            $mnStoreGoods = $mnStoreGoodsAll[$value['goods_id']] ?? '';
            if (!empty($mnStoreGoods) && $mnStoreGoods == 1) {
                $item                 = $value;
                $item['name']         = $goodsAll[$value['goods_id']]['name'] ?? '';
                $profits              = $profitAll[$value['goods_id']] ?? [];
                $item['price_store']  = $profits['price_store'];
                $item['price_retail'] = sprintf("%.2f", round($profits["profit"] + $profits['price_store']));
                $resultData[]         = $item;
            }
        }
        return Normal::returnCode(Normal::SUC, '获取成功', ['data' => $resultData, 'count' => $result->total()]);
    }

    /**
     * 修改活动
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function editActivity(array $param)
    {
        if (!isset($param['activity_id']) || empty($param['activity_id']) || (preg_match("/^[1-9]\d*$/", (string)$param['activity_id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument activity_id');
        }
        if (!isset($param['mn_sid']) || empty($param['mn_sid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mn_sid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mn_sid');
        }
        if (!isset($param['name']) || empty($param['name'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument name');
        }
        if (!isset($param['startdate']) || empty($param['startdate'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument startdate');
        }
        if (!isset($param['enddate']) || empty($param['enddate'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument enddate');
        }
        if (!isset($param['type']) || !in_array($param['type'], ['1', '2'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument type');
        }
        if (!isset($param['status']) || !in_array($param['status'], ['1', '2', '3'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument status');
        }
        if (!isset($param['goods']) || empty($param['goods'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument goods');
        }
        $activity = MnActivity::where('id', (int)($param['activity_id']))->first();
        if (!$activity) {
            return Normal::returnCode(Normal::FAIL, '未找到相关活动');
        }
        $startdate = $param['startdate'];
        $enddate   = $param['enddate'];
        $goods     = json_decode($param['goods'], true);
        $goods_ids = array_column($goods, 'goods_id');
        $goodsAll  = Goods::whereIn('id', $goods_ids)->select(['id', 'medicinal', 'price_store', 'name', 'price_cost', 'is_trade'])->get()->toArray();
        if ($goodsAll) {
            $goodsAll = array_column($goodsAll, null, 'id');
        }
        $existByGoods = [];
        $existAll     = MnActivityGoods::query()->from((new MnActivityGoods)->getTable() . ' as mnag')
            ->join("ly_mn_activity as mna", 'mnag.mn_activity_id', '=', 'mna.id')
            ->leftJoin('ly_goods as gs', 'gs.id', '=', 'mnag.goods_id')
            ->where('mna.mn_sid', (int)($param['mn_sid']))->whereIn('mnag.goods_id', $goods_ids)->where('mnag.df', 0)
            ->where('mna.id', '<>', (int)($param['activity_id']))
            ->where(function ($query) use ($startdate, $enddate) {
                $query->whereBetween('mna.startdate', [$startdate, $enddate])->orWhereBetween('mna.enddate', [$startdate, $enddate]);
            })->select(['mna.id', 'mnag.goods_id', 'gs.name as goods_name', 'mna.enddate'])->get()->toArray();
        if ($existAll) {
            foreach ($existAll as $item) {
                $existByGoods[$item['goods_id']][] = $item;
            }
        }
        foreach ($goods as $key => $value) {
            if ($param['type'] == 2 && !isset($value['price'])) {
                return Normal::returnCode(Normal::FAIL, '请设置完商品的特价价格');
            }
            $goodsType = $goodsAll[$value['goods_id']];
            if (isset($goodsType['is_trade']) && $goodsType['is_trade'] == 0) {
                if ($value['price'] < $goodsType['price_store']) {
                    return Normal::returnCode(Normal::FAIL, "商品《{$goodsType['name']}》不可低于成本价");
                }
            }
            $exist = $existByGoods[$value['goods_id']] ?? [];
            if ($exist) {
                foreach ($exist as $v) {
                    if ($v['enddate'] > time()) {
                        return Normal::returnCode(Normal::FAIL, $v['goods_name'] . '商品在其他可进行时间内的活动中已经存在');
                    }
                }
            }
        }
        $activity->name      = $param['name'];
        $activity->startdate = $startdate;
        $activity->enddate   = $enddate;
        $activity->md        = time();
        $activity->mn_sid    = (int)($param['mn_sid']);
        $activity->type      = (int)($param['type']);
        $activity->status    = (int)($param['status']);
        if ($param['type'] == 1) {
            if (!isset($param['full']) || !isset($param['drop'])) {
                return Normal::returnCode(Normal::FAIL, '请设置满减金额');
            }
            $activity->full = $param['full'];
            $activity->drop = $param['drop'];
        }
        Db::beginTransaction();
        try {
            $mnActivityModelRes = $activity->save();
            if (!$mnActivityModelRes) {
                throw new \RuntimeException("活动保存异常");
            }
            $activityGoodsDatra = [];
            foreach ($goods as $val) {
                $activityGoodsDatra[] = [
                    'mn_activity_id' => $activity->id,
                    'cd'             => time(),
                    'sid'            => getSID(),
                    'goods_id'       => (int)($val['goods_id']),
                    'price'          => $val['price'],
                ];
            }
            //先删除之前的商品
            MnActivityGoods::where('mn_activity_id', $activity->id)->update(['df' => 1, 'md' => time()]);
            $activityGoodsRes = MnActivityGoods::insert($activityGoodsDatra);
            if (!$activityGoodsRes) {
                throw new \RuntimeException("活动商品保存错误");
            }
            Db::commit();
        } catch (\Throwable $th) {
            Db::rollBack();
            return Normal::returnCode(Normal::FAIL, '操作失败' . $th->getMessage());
        }
        return Normal::returnCode(Normal::SUC, '操作成功');

    }

    /**
     * 当日特价活动
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function seckillList(array $param)
    {
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        if (!isset($param['mn_sid']) || empty($param['mn_sid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mn_sid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mn_sid');
        }
        $curTsp = time();
        $result = MnActivity::where('mn_sid', (int)($param['mn_sid']))->where('df', 0)
            ->where('type', 2)->where('startdate', '<=', $curTsp)->where('enddate', '>', $curTsp)
            ->where('status', 1)->select(['id', 'name', 'startdate', 'enddate'])
            ->orderByRaw("startdate asc, enddate asc")->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功');
        }
        $result->each(function ($item, $key) use ($curTsp) {
            $item->now_time = $curTsp;
            return $item;
        });
        return Normal::returnCode(Normal::SUC, '获取成功', $result->items());
    }

    /**
     * 场次内容
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function seckillItem(array $param)
    {
        if (!isset($param['seckill_id']) || empty($param['seckill_id']) || (preg_match("/^[1-9]\d*$/", (string)$param['seckill_id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument seckill_id');
        }
        if (!isset($param['mn_sid']) || empty($param['mn_sid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mn_sid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mn_sid');
        }
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        $mnUser = Mnuser::where('id', $param['mn_sid'])->where('new_store', 1)->first();
        if (empty($mnUser)) {
            return Normal::returnCode(Normal::FAIL, 'Q店不存在');
        }
        $mnActivityModel = MnActivity::where('id', (int)($param['seckill_id']))->where('mn_sid', (int)($param['mn_sid']))->where('type', 2);
        if (!isset($param['is_admin']) || $param['is_admin'] != 1) {
            $mnActivityModel = $mnActivityModel->where('status', 1);
        }
        $seckill = $mnActivityModel->first();
        if (empty($seckill)) {
            return Normal::returnCode(Normal::FAIL, '场次不存在');
        }
        $result = MnActivityGoods::query()->from((new MnActivityGoods)->getTable() . ' as mag')
            ->leftJoin('ly_mn_store_goods as mg', 'mg.goods_id', '=', 'mag.goods_id')
            ->leftJoin('ly_goods as g', 'g.id', '=', 'mg.goods_id')
            ->where('mag.mn_activity_id', (int)($param['seckill_id']))->where('mg.mn_sid', (int)($param['mn_sid']))
            ->where('mag.df', 0)->where(function ($query) use ($mnUser) {
                if ($mnUser->type == 2) {
                    $query->whereRaw("((g.status=1 and g.df=0 and g.is_trade=0) or (g.is_trade=1 and (mg.df=0 or (mg.df=1 and mg.num>0) or (mg.pre_sell=1 and mg.pre_storage>0))))");
                } else {
                    $query->where('g.is_trade', 0);
                }
            })->where(function ($query) use ($mnUser) {
                if ($mnUser->type == 3) {
                    $supplier_id = (int)($mnUser->supplier_id);
                    switch ($mnUser->goods_source) {
                        case 1://只卖普通仓
                            $query->whereRaw("(g.is_fast_delivery=0)");
                            break;
                        case 2://只卖前置仓
                            $query->whereRaw("(g.supplier_id={$supplier_id})");
                            break;
                        case 3://前置仓+普通仓
                            $query->whereRaw("((g.supplier_id={$supplier_id}) or (g.is_fast_delivery=0))");
                            break;
                        case 4://只卖中心仓
                            $query->whereRaw("(g.is_fast_delivery=2)");
                            break;
                        case 5://中心仓+普通仓
                            $query->whereRaw("(g.is_fast_delivery<>1)");
                            break;
                        case 6://中心仓+前置仓
                            $query->whereRaw("((g.supplier_id={$supplier_id}) or (g.is_fast_delivery=2))");
                            break;
                        case 7://所有仓
                            $query->whereRaw("((g.supplier_id={$supplier_id}) or (g.is_fast_delivery in (0,2)))");
                            break;
                    }
                } else {
                    $query->whereRaw("(g.is_fast_delivery <> 1)");
                }
            })->select(['mag.goods_id', 'mag.price as price_seckill'])->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功');
        }
        $collection      = $result->getCollection();
        $goods_ids       = $collection->pluck('goods_id')->toArray();
        $goodsAll        = MnGoodsService::getGoodsListByGoodsIds($goods_ids, (int)($mnUser->pid), (int)($param['mn_sid']));
        $mnStoreGoodsAll = MnStoreGoods::whereIn('goods_id', $goods_ids)->where('mn_sid', (int)($param['mn_sid']))->pluck('status', 'goods_id')->toArray();
        $is_vip          = [];
        if (isset($param['mid']) && !empty($param['mid'])) {
            $is_vip = Vip::check(['mid' => $param['mid'], 'mn_sid' => $param['mn_sid']]);
        }
        $resultArr  = $collection->toArray();
        $curTsp     = time();
        $resultData = [];
        foreach ($resultArr as $value) {
            $storeGoods = $mnStoreGoodsAll[$value['goods_id']] ?? '';
            $goods      = $goodsAll[$value['goods_id']] ?? [];
            if (empty($goods)) {
                continue;
            }
            if (($goods['is_trade'] == 0) && $goods['status'] != 1) {
                continue;
            }
            if (empty($storeGoods)) {
                continue;
            }
            $item          = $value;
            $item['price'] = sprintf("%.2f", round($goods['price'], 2));
            if ($is_vip) {
                if ($is_vip['is_vip'] == 1) {
                    $item['price'] = sprintf("%.2f", round($goods['price_vip'], 2));
                }
            }
            $item['start_time'] = $seckill['startdate'];
            $item['end_time']   = $seckill['enddate'];
            $item['now_time']   = $curTsp;
            $item['goods']      = $goods;
            $resultData[]       = $item;
        }
        return Normal::returnCode(Normal::SUC, '获取成功', $resultData);
    }

    /**
     * 商品促销详情
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getFormatDetail(array $param)
    {
        if (!isset($param['activity_id']) || empty($param['activity_id']) || (preg_match("/^[1-9]\d*$/", (string)$param['activity_id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument activity_id');
        }
        if (!isset($param['mn_sid']) || empty($param['mn_sid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mn_sid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mn_sid');
        }
        if (!isset($param['cid']) || empty($param['cid']) || (preg_match("/^[1-9]\d*$/", (string)$param['cid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        $param['activity_id'] = (int)($param['activity_id']);
        $param['cid']         = (int)($param['cid']);
        $param['mn_sid']      = (int)($param['mn_sid']);
        $param['mid']         = (int)($param['mid']);
        $info                 = Activity::where('id', $param['activity_id'])->where('cid', $param['cid'])->first();
        if (!$info) {
            return Normal::returnCode(Normal::FAIL, '活动不存在');
        }
        $info = $info->toArray();
        if ($param['mnid'] == 4) {
            $isVip['is_vip'] = 0;
            if ($param['mid']) {
                $isVip = Vip::check(['mid' => $param['mid'], 'mn_sid' => $param['mn_sid']]);
            }
            if (empty($param['mid']) || $isVip['is_vip'] == 0) {
                if ($info['target_type'] == 3) {
                    return Normal::returnCode(Normal::FAIL, '此活动只适用黑卡会员用户');
                }
            }
            if ($isVip['is_vip'] == 1) {
                if ($info['target_type'] == 2) {
                    return Normal::returnCode(Normal::FAIL, '此活动只适用普通会员用户');
                }
            }
            if ($info['sync_online'] == 2) {
                return Normal::returnCode(Normal::FAIL, '此活动只适用线下门店');
            }
            $ban = StoreActivity::where('mn_sid', $param['mn_sid'])->where('activity_id', $info['id'])->exists();
            if ($ban) {
                return Normal::returnCode(Normal::FAIL, '此活动店铺已禁用');
            }
        }
        $store  = ActivityStore::where('activity_id', $info['id'])->get()->toArray();
        $stores = array_column($store, 'mn_sid');
        if ($store[0]['mn_sid'] != 0 && !in_array($param['mn_sid'], $stores)) {
            return Normal::returnCode(Normal::FAIL, '此活动不适用当前店铺');
        }
        if (in_array($info['type'], [1, 2])) {
            switch ($info['rule_type']) {
                case 1://买赠
                    $res = ActivitySend::getContent(['activity_id' => $info['id']]);
                    break;
                case 2://直降
                    $res = ActivityDrop::getContent(['activity_id' => $info['id']]);
                    break;
                case 3://打折
                    $res = ActivityDiscount::getContent(['activity_id' => $info['id']]);
                    break;
                default:
                    $res = ['code' => Normal::FAIL];
            }
            if ($res['code'] == Normal::SUC) {
                $content            = $res['data']['content'];
                $data['send_goods'] = $res['data']['sendGoods'] ?? null;
            } else {
                $content = "未知活动规则";
            }
        } else {
            $content = '';
            if ($info['type'] == 4) {
                $book   = ActivityBook::where('activity_id', $info['id'])->value('num');
                $number = explode(',', $book['num']);
                foreach ($number as $v) {
                    $content .= $v . '人拼团、';
                }
                $content = rtrim('、', $content);
            }
            $time_start_str = strtotime($info['begintime']);
            $time_end_str   = strtotime($info['endtime']);
            $curTsp         = time();
            if ($curTsp > $info['begindate'] && $curTsp >= $time_start_str && $curTsp <= $time_end_str) {
                $data['tag']       = '抢购中';
                $data['show_time'] = date('H:i', strtotime($info['begintime']));
            }
            if ($curTsp > $info['begindate'] && ($curTsp < $time_start_str || $curTsp > $time_end_str)) {
                $data['tag']       = '即将开始';
                $data['show_time'] = date('H:i', strtotime($info['begintime']));
            }
            if ($curTsp < $info['begindate']) {
                $data['tag']       = '即将开始';
                $data['show_time'] = date('m-d', $info['begindate']) . ' ' . date('H:i', strtotime($info['begintime']));
            }
            if ($curTsp > $info['begindate'] && $curTsp > $time_end_str && date('Y-m-d', $curTsp) == date('Y-m-d', $info['enddate'])) {
                $data['tag']       = '已结束';
                $data['show_time'] = '';
            }
        }
        $data['activity_id'] = $param['activity_id'];
        $data['name']        = $info['name'];
        $data['body']        = $content;
        switch ($info['target_type']) {
            default:
            case 1:
                $data['member'] = '全场';
                break;
            case 2:
                $data['member'] = '普通会员';
                break;
            case 3:
                $data['member'] = '黑卡会员';
                break;
        }
        $data['time'] = date('Y-m-d', $info['begindate']) . ' 至 ' . date('Y-m-d', $info['enddate']) . ' 每天' . $info['begintime'] . ' 至 ' . $info['endtime'];
        return Normal::returnCode(Normal::SUC, '获取成功', $data);
    }
}